import React, { createContext, useContext, useState } from 'react';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

// 默认语言资源
import en from '@/components/common/translation/en.json';
import zh from '@/components/common/translation/zh.json';

// 初始化 i18n 实例
i18n.use(initReactI18next).init({
    resources: {
        en: { translation: en },
        zh: { translation: zh },
    },
    lng: 'zh', // 默认语言
    fallbackLng: 'zh',
    interpolation: { escapeValue: false },
});

// 定义上下文类型
interface TranslationContextType {
    lang: string;
    changeLanguage?: (language: string) => void;
}

// 创建上下文
const TranslationContext = createContext<TranslationContextType | null>(null);

const TranslationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [lang, setLang] = useState('en');

    const changeLanguage = (language: string) => {
        setLang(language);
        i18n.changeLanguage(language); // 切换语言
    };

    return (
        <TranslationContext.Provider value={{ lang, changeLanguage }}>
            {children}
        </TranslationContext.Provider>
    );
};

// 自定义 hook 用于消费上下文
export const useTranslationContext = () => {
    const context = useContext(TranslationContext);
    if (!context) {
        throw new Error('useTranslationContext must be used within a TranslationProvider');
    }
    return context;
};

export default TranslationProvider;
